package cn.restcloud.example.controller;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import cn.restcloud.framework.client.RestClient;
import cn.restcloud.framework.core.annotation.bean.BeanConfig;
import cn.restcloud.framework.core.annotation.bean.BeanType;
import cn.restcloud.framework.core.annotation.rest.MethodType;
import cn.restcloud.framework.core.annotation.rest.RestAuthType;
import cn.restcloud.framework.core.annotation.rest.RestConfig;
import cn.restcloud.framework.core.annotation.rest.RestRequestBody;
import cn.restcloud.framework.core.container.BeanFactory;
import cn.restcloud.framework.core.context.AppContext;
import cn.restcloud.framework.core.util.CommonUtil;
import cn.restcloud.framework.core.util.ConfigUtil;
import cn.restcloud.framework.core.util.DocumentUtil;
import cn.restcloud.framework.core.util.LogUtil;
import cn.restcloud.framework.core.util.RequestUtil;
import cn.restcloud.framework.login.service.JwtTokenService;
import cn.restcloud.framework.org.model.P_OrgPersonContext;
import cn.restcloud.framework.org.service.OrgPersonLogic;
import cn.restcloud.framework.org.service.PersonUtil;
import cn.restcloud.framework.view.base.DocAndView;
import cn.restcloud.framework.view.util.ViewUtil;

@BeanConfig(appId = "base",beanId = "JdCloudLoginRest",beanName = "京东云单点登录集成",beanType = BeanType.CONTROLLER)
public class JdCloudLoginRest {
	private String apiBaseUrl="https://nf-server.jdcloud.com:8080/restcloud";
	private String baseUrl="https://oauth2.jdcloud.com";
	private String client_id="";
	private String pwd="guowang@2020";
	private String ssoUrl=apiBaseUrl+"/sso";
	private String adminHomePage=apiBaseUrl+"/admin/esb";
	private String jdLoginUrl=baseUrl+"/authorize?response_type=code&redirect_uri="+ssoUrl+"&client_id="+client_id+"&state="+DocumentUtil.getNewDocumentId();
	
	@RestRequestBody
	@RestAuthType("0")
	@RestConfig(configName = "访问本API跳转到JD云进行登录",method = MethodType.GET,url = "/login")
	public DocAndView sso() throws Exception{
		DocAndView dv=ViewUtil.getJsonView();
		String userId=AppContext.getUserId();
		if(!userId.equalsIgnoreCase(PersonUtil.ANONYMOUS)) {
			jdLoginUrl=adminHomePage; //用户已经登录跳转到登录界面
		}
		dv.setResponseCode(302);
		dv.getResponseHeader().put("Location",jdLoginUrl); //用户登录成功后的重定向url
		return dv;
	}
	

	@RestRequestBody
	@RestAuthType("0")
	@RestConfig(configName = "JD登录后会重定向到本API",method = MethodType.GET,url = "/sso")
	public DocAndView listUsers() throws Exception{
		DocAndView dv=ViewUtil.getJsonView();
		dv.setResponseCode(302);
		String userId=AppContext.getUserId();
		
		//请求令牌端点（Token Endpoint）
		Document userDoc=new Document();
		String userName="";
		String code=RequestUtil.getString("code");
		String tokenUrl=baseUrl+"/token?grant_type=authorization_code&code="+code;
		String basic="Basic "+CommonUtil.enBase64(client_id+":"+pwd);
		Document tokenDoc=RestClient.getInstance().setUrl(tokenUrl).addToken(false).addHeaders("Authorization", basic).get().getDocument();
//		PrintUtil.o("tokendoc="+tokenDoc);
		String access_token=tokenDoc.getString("access_token");
		if(StringUtils.isNotBlank(access_token)) {
			String userUrl=baseUrl+"/userinfo";
			String accessAuth="Bearer "+access_token;
			userDoc=RestClient.getInstance().setUrl(userUrl).addToken(false).addHeaders("Authorization", accessAuth).get().getDocument();
//			PrintUtil.o("userDoc==="+userDoc);
			userId=userDoc.getString("account");
			userName=userDoc.getString("name");
			if(StringUtils.isNotBlank(userId)) {
				//说明用户登录成功
				HttpServletResponse response=AppContext.getResponse();
				
				//创建一个用户并给开发者权限
				List<String> permissionId=new ArrayList<String>();
				permissionId.add("core.appdesigner"); //给一个应用开发者角色
				OrgPersonLogic personLogic=BeanFactory.getBean(OrgPersonLogic.class);
	    		P_OrgPersonContext personContext=personLogic.getPersonContext(userId, "");
	    		personContext.setUserName(userId);
	    		personContext.setPermissionId(permissionId);
				AppContext.setUserId(userId);
				
				//给登录用户发放token
				String identitytoken=JwtTokenService.getToken(userId);
				Cookie cookie = new Cookie(JwtTokenService.TOKENKEY, identitytoken);
				String cookieDomain=ConfigUtil.getConfig("CookieDomain");
				cookieDomain="";
				if(StringUtils.isNotBlank(cookieDomain)){
					cookie.setDomain(cookieDomain);
				}
				cookie.setPath("/");
				response.addCookie(cookie);
				
    			Cookie cookie2 = new Cookie("userName",userName); //写一个cookie到浏览器中
    			cookie2.setDomain(cookieDomain);
    			cookie2.setPath("/");
    			response.addCookie(cookie2);
    			
    			dv.getResponseHeader().put("Location",adminHomePage); //用户登录成功后的重定向url
//    			PrintUtil.o("用户cookie="+identitytoken);
    			return dv;
			}
		}else{
			LogUtil.info("单点登录失败!");
			dv.getResponseHeader().put("Location",jdLoginUrl); //用户登录成功后的重定向url
		}
		
		return dv;
	}

	
}
